import Socket from '@/model/Socket'
import { getCookie } from '@/utils/tools'

export function getSocketBaseUrl () {
  const localurl = window.location.href.split('/')
  const basePath = localurl[2]
  return process.env.NODE_ENV === 'development'
    ? process.env.VUE_APP_WEBSOCKET_URL
    : `ws://${basePath}`
}

export default {
  state: {
    socket: null

  },

  mutations: {
    'SET_GLOBLE_SOCKET' (state, socket) {
      state.socket = socket
    }
  },

  actions: {
    openGlobleSocket ({ state, commit }) {
      if (!state.socket) {
        let socket = new Socket({
          url: getSocketBaseUrl() + '/gov-websocket/websocket/' + getCookie('UID')
        })
        commit('SET_GLOBLE_SOCKET', socket)
      }
      state.socket.on('message', message => {
        switch (message.data_type) {
          case 'car_io':
            commit('UPDATE_IO_SOCKET_DATA', message.data)
            break
          case 'parking_io':
            commit('UPDATE_PARK_SOCKET_DATA', message.data)
            break
          case 'important_car':
            commit('UPDATE_KEY_IO_SOCKET_DATA', message.data)
            break
          default:
            break
        }
      })
      state.socket.on('error', () => {

      })
      state.socket.on('close', () => {
      })
    },
    destroyGlobleSocket ({ state, commit }) {
      if (state.socket) {
        state.socket.close()
        commit('SET_GLOBLE_SOCKET', null)
      }
      commit('CLEAR_IO_COLLECT')
      commit('CLEAR_KEY_IO_COLLECT')
      commit('CLEAR_PARK_COLLECT')
    }
  }
}
